﻿using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace IntoCommon.Protocol
{
    public class ModbusTcp
    {
        public ModbusTcp(string ip,int port)
        {
            this.ip = ip;
            this.port = port;            
        }

        private string ip;
        private int port;
        private TcpClient client;
        public IModbusMaster Master { get; set; }
        public bool Connect()
        {
            if(Master != null)
            {
                Master.Dispose();
            }
            if(client != null)
            {
                client.Close();
            }
            try
            {
                client = new TcpClient();
                IAsyncResult ayncResult = client.BeginConnect(ip, port, null, null);
                ayncResult.AsyncWaitHandle.WaitOne(3000,true);
                if(!ayncResult.IsCompleted || !client.Connected)
                {
                    client.Close();
                    return false;
                }
                Master = ModbusIpMaster.CreateIp(client);
                Master.Transport.Retries = 0;
                Master.Transport.ReadTimeout = 1500;
                return true;
            }
            catch
            {
                return false;
            }
        }
        
    }
}
